#!/usr/bin/python

import re
import os
import feedparser
from urllib2 import Request, urlopen, URLError, HTTPError
import sqlite3 as sqlite

def downTor(torurl, getitel):
		try:
			f = urlopen(torurl)
		except HTTPError:
			return false
		top = fi.match(torurl)
		if top:
			file_name = top.group(1)
		else:
			file_name = getitel
		local_file = open(file_name, "w")
		local_file.write(f.read())
		local_file.close()
		return True


conn = sqlite.connect('gnur_series_database.db')
cursor = conn.cursor()
cursor.execute ("SELECT naam,regu FROM series")
series = []
for row in cursor: 
	series.append(row)

cursor.execute ("SELECT url FROM urls")
feeds = []
for row in cursor:
	feeds.append(row[0])

s = re.compile('.*([0-9]+)[xE]([0-9]+).*', re.I)
dmy = re.compile('.*2011\.?\s?(\d\d)\.?\s?(\d\d).*', re.I)
fi = re.compile('.*\/(.*\.torrent)', re.I)
for a in feeds:
	d = feedparser.parse(a)
	niks = True
	for g in d.entries:
		for serie in series:
			p = re.compile(serie[1], re.I)
			if p.match(g.title):
				seiz = s.match(g.title)
				if seiz:
					cursor.execute("SELECT id FROM serie_download WHERE serie = '" + serie[0] + "' AND seizoen = " + seiz.group(1) + " AND aflevering = " + seiz.group(2))
					conn.commit()
					row = cursor.fetchone()
					if row == None:
						if downTor(g.link, g.title):							
							cursor.execute("INSERT INTO serie_download (seizoen, aflevering, serie) VALUES (" + seiz.group(1) + ", " + seiz.group(2) + ", '" + serie[0] + "')")
				else:
					datum = dmy.match(g.link)
					if datum:
						cursor.execute("SELECT id FROM serie_download WHERE serie = '" + serie[0] + "' AND seizoen = " + datum.group(1) + " AND aflevering = " + datum.group(2))
						row = cursor.fetchone()
						if row == None:
							if downTor(g.link, g.title):
								cursor.execute("INSERT INTO serie_download (seizoen, aflevering, serie, toegevoegd) VALUES (" + datum.group(1) + ", " + datum.group(2) + ", '" + serie[0] + "','NOW')")
					

conn.commit()
cursor.close ()
conn.close ()